package com.tomorrow.runner.service.impl;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import com.tomorrow.runner.data.bean.UserBean;
import com.tomorrow.runner.data.model.UserModel;
import com.tomorrow.runner.service.IBasicService;
import com.tomorrow.runner.service.Result;
import com.tomorrow.runner.service.api.IAccountService;
import com.tomorrow.runner.util.RunnerError;

import cn.sucun.android.codec.digest.DigestUtils;
import cn.sucun.android.utils.Preferences;

/**
 *
 * Created by tomorrow on 16-4-27.
 */
class AccountService implements IBasicService,IAccountService{

    private static final String CURRENT_USER = "current_user";
    private ServiceManager mManager;
    private ContentResolver mContentResolver;
    private Preferences mPreferences;
    public AccountService(ServiceManager manager){
        mManager = manager;
        mContentResolver = manager.mContext.getContentResolver();
        mPreferences = Preferences.getCommon(manager.mContext);
    }
    public Result login(String username, String pwd){
        Result result = new Result();
        UserBean userBean = _getUserInfo(username);
        if (userBean == null){
            result.setError(RunnerError.getErrorWothText("账户不存在"));
            return result;
        }
        pwd =  DigestUtils.sha1Hex(pwd);
        if (!userBean.pwd.equalsIgnoreCase(pwd)){
            result.setError(RunnerError.getErrorWothText("密码错误"));
            return result;
        }
        mManager.onLogin(username);
        return result;
    }

    public Result logout(String username){
        mManager.onLogout(username);
        return new Result();
    }

    public Result register(UserBean userBean){
        Result result = new Result();
        if (userBean == null){
            result.setError(RunnerError.getErrorWothText("信息为空"));
            return result;
        }
        if (_getUserInfo(userBean.username) != null){
            result.setError(RunnerError.getErrorWothText("用户已存在"));
            return result;
        }
        ContentValues values = new ContentValues();
        values.put(UserModel.USERNAME,userBean.username);
        values.put(UserModel.PASSWORD,DigestUtils.sha1Hex(userBean.pwd));
        values.put(UserModel.GANDER,userBean.gender);
        values.put(UserModel.NICKNAME,userBean.nickname);
        values.put(UserModel.BIRTHDAY,userBean.birthday);
        values.put(UserModel.WEIGHT,userBean.weight);
        values.put(UserModel.TALL,userBean.tall);
        Uri uri =  mContentResolver.insert(UserModel.getContentUri(),values);
        if (ContentUris.parseId(uri) < 0){
            result.setError(RunnerError.getErrorWothText("写入数据库失败"));
        }
        return result;
    }

    @Override
    public Result updateUser(UserBean userBean) {
        Result result = new Result();
        if (userBean == null){
            result.setError(RunnerError.getErrorWothText("信息为空"));
            return result;
        }
        if (_getUserInfo(userBean.username) == null){
            result.setError(RunnerError.getErrorWothText("用户不存在"));
            return result;
        }
        ContentValues values = new ContentValues();
        if (!TextUtils.isEmpty(userBean.pwd)){
            values.put(UserModel.PASSWORD,DigestUtils.sha1Hex(userBean.pwd));
        }
        values.put(UserModel.GANDER,userBean.gender);
        values.put(UserModel.NICKNAME,userBean.nickname);
        values.put(UserModel.BIRTHDAY,userBean.birthday);
        values.put(UserModel.WEIGHT,userBean.weight);
        values.put(UserModel.TALL,userBean.tall);
        String where = UserModel.USERNAME+"=?";
        String[] args = {userBean.username};
        int count = mContentResolver.update(UserModel.getContentUri(),values,where,args);
        if (count < 0){
            result.setError(RunnerError.getErrorWothText("写入数据库失败"));
        }
        return result;
    }

    @Override
    public UserBean getUserInfo() {
        String account = mPreferences.getString(CURRENT_USER,"");
        UserBean userBean = _getUserInfo(account);
        if (userBean == null ){
            return null;
        }
        userBean.pwd = "";
        return userBean;
    }

    @Override
    public boolean isLogin() {
        return !TextUtils.isEmpty(mPreferences.getString(CURRENT_USER,""));
    }


    @Override
    public void onLogin(String username) {
        mPreferences.edit().putString(CURRENT_USER,username).apply();
    }

    @Override
    public void onLogout(String username) {
        mPreferences.edit().putString(CURRENT_USER,"").apply();
    }

    private UserBean _getUserInfo(String account){
        UserBean userBean = new UserBean();
        Cursor cursor = mContentResolver.query(UserModel.getContentUri(),null,
                UserModel.USERNAME +"=?",new String[]{account},null);
        if (cursor == null || cursor.getCount() <= 0){
            return null;
        }
        if (cursor.moveToFirst()){
            userBean.username = account;
            userBean.pwd = cursor.getString(cursor.getColumnIndexOrThrow(UserModel.PASSWORD));
            userBean.gender = cursor.getInt(cursor.getColumnIndexOrThrow(UserModel.GANDER)) == 1;
            userBean.birthday = cursor.getLong(cursor.getColumnIndexOrThrow(UserModel.BIRTHDAY));
            userBean.nickname = cursor.getString(cursor.getColumnIndexOrThrow(UserModel.NICKNAME));
            userBean.weight = cursor.getLong(cursor.getColumnIndexOrThrow(UserModel.WEIGHT));
            userBean.tall = cursor.getLong(cursor.getColumnIndexOrThrow(UserModel.TALL));
        }
        cursor.close();
        return userBean;
    }
}
